package com.itheima.controller.admin;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 下载模板文件
     * @param filename
     */
    @GetMapping("/download")
    public void test(HttpServletResponse response, String filename){
        log.info("下载模板文件,filename:{}",filename);
        try {
            String path = this.getClass().getClassLoader().getResource("").getPath() + "\\templates\\" + filename;
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile){
        log.info("文件上传:{}", excelFile);
        try {
            List<Map<String,String>> ls = new ArrayList<>();
            InputStream in = excelFile.getInputStream();
            //通过输入流读取指定的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取Excel文件的第1个Sheet页
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取Sheet页中的最后一行的行号
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                //获取Sheet页中的行
                XSSFRow titleRow = sheet.getRow(i);
                //获取行的第1个单元格
                XSSFCell cell1 = titleRow.getCell(0);
                //获取单元格中的文本内容
                Date cellValue1 = cell1.getDateCellValue();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(cellValue1);
                //获取行的第2个单元格
                XSSFCell cell2 = titleRow.getCell(1);
                //获取单元格中的文本内容
                Integer cellValue2 = (int)cell2.getNumericCellValue();

                Map map = new HashMap();
                map.put("orderDate", format);
                map.put("number", cellValue2);
                map.put("reservations", 0);
                ls.add(map);
            }
            in.close();
            excel.close();
            orderSettingService.insertBatch(ls);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /**
     * 预约管理列表
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month){
        log.info("预约管理列表,month:{}", month);
        List<Map<String,String>> orderSettingList = orderSettingService.getOrderSettingByMonth(month);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettingList);
    }

    /**
     * 修改可预约人数
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderDate){
        log.info("修改可预约人数, orderDate:{}", orderDate.getOrderDate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(orderDate.getOrderDate());
        orderSettingService.updateNumber(orderDate.getNumber(), format);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }
}
